package mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by dengpan on 2016/12/2.
 */
public class M1 {
    public static void main(String[] args)  throws Exception {

        try {
            //调用Class.forName()方法加载驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("成功加载MySQL驱动！");
        } catch (ClassNotFoundException e1) {
            System.out.println("找不到MySQL驱动!");
            e1.printStackTrace();
        }

        String url = "jdbc:mysql://192.168.56.101:3306/test";    //JDBC的URL
        //调用DriverManager对象的getConnection()方法，获得一个Connection对象
        Connection conn;
        try {
            conn = DriverManager.getConnection(url, "root", "201479");

            //①带参数的查询
            String sql = "select * from t1 where id > ? and name = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql); //创建Statement对象
            pstmt.setInt(1, 0);
            pstmt.setString(2, "ss");
            ResultSet rs = pstmt.executeQuery();
            System.out.println("id\tname\tage");
            while (rs.next()) {
                System.out.println(String.format("%d\t%s\t\t%d", rs.getInt("id"), rs.getString("name"), rs.getInt("age")));
            }
            Thread.sleep(100000);


            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
